//
//  ImageUpload.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/6/14.
//

import Foundation
import UIKit
import Photos
import YYCategories

final class ImageUpload: NSObject {
    
    static let shared = { () -> ImageUpload in
        let instance = ImageUpload()
        // 其他代码
        return instance
    }()
    
    private override init() {}
    
    private lazy var imagePickerController: UIImagePickerController = {
        let imagePickerController = UIImagePickerController.init()
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = true
        imagePickerController.modalPresentationStyle = .overFullScreen
        return imagePickerController
    }()
    
    typealias UploadBlock = (_ image: UIImage) -> Void
    var block: UploadBlock?
}



extension ImageUpload {
    func addImageUploadBlock(block: @escaping UploadBlock) {
        self.block = block
        
        let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        let cameraAction = UIAlertAction.init(title: "拍照", style: .default) { action in
            self.checkCameraPermission()//检查相机权限
        }
        let photoAction = UIAlertAction.init(title: "从手机相册选择", style: .default) { action in
            self.checkAlbumPermission()//检查相册权限
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alertController.addAction(cameraAction)
        alertController.addAction(photoAction)
        alertController.addAction(cancelAction)
        UIWindow().currentViewController()?.present(alertController, animated: true, completion: nil)
    }
    
    private func checkCameraPermission() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        if status == .notDetermined {
            AVCaptureDevice.requestAccess(for: .video) { granted in
                if granted {
                    self.takePhoto()
                }
            }
        } else if (status == .denied || status == .restricted) {
            self.alertalbum(string: "请在设置中打开相机权限")
        } else {
            self.takePhoto()
        }
    }
    
    private func checkAlbumPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
//        switch status {
//        case .notDetermined:
//            //用户还没有对这个应用程序做出选择
//            PHPhotoLibrary.requestAuthorization() { phStatus in
//                if phStatus == .authorized {
//                    self.selectAlbum()
//                }
//            }
//        case .restricted:
//            //此应用程序未被授权访问照片数据
//            self.alertalbum(string: "请在设置中打开相册权限")
//        case .denied:
//            //用户已明确拒绝此应用程序访问照片数据
//            self.alertalbum(string: "请在设置中打开相册权限")
//        case .authorized:
//            //用户已授权此应用程序访问照片数据
//            self.selectAlbum()
//        case .limited:
//            //用户已授权此应用程序访问有限的照片库。添加phphotolibrarypreventautomaticliitedaccessalert = YES到应用程序的信息。防止Plist自动提醒更新用户有限的库选择。使用[phphotollibrary (PhotosUISupport) presentLimitedLibraryPickerFromViewController:] from PhotosUI/ phphotollibrary +PhotosUISupport.h来手动显示有限库选择器。
//            self.selectAlbum()
//        default:
//            break
//        }
        
        
        if status == .notDetermined {
            PHPhotoLibrary.requestAuthorization() { phStatus in
                if phStatus == .authorized {
                    self.selectAlbum()
                }
            }
        } else if (status == .denied || status == .restricted) {
            self.alertalbum(string: "请在设置中打开相册权限")
        } else {
            self.selectAlbum()
        }
    }
    
    private func takePhoto() {
        dispatch_async_on_main_queue {
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePickerController.sourceType = .camera
                UIWindow().currentViewController()?.present(self.imagePickerController, animated: true, completion: nil)
                
            } else {
                self.alertalbum(string: "不能使用模拟器进行拍照")
            }
            
        }
        
    }
    
    private func alertalbum(string: String) {
        dispatch_async_on_main_queue {
            let alert = UIAlertController(title: nil, message: string, preferredStyle: .alert)
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(cancel)
            UIWindow().currentViewController()?.present(alert, animated: true, completion: nil)
        }
        
    }
    
    private func selectAlbum() {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            dispatch_async_on_main_queue {
                self.imagePickerController.sourceType = .photoLibrary
                UIWindow().currentViewController()?.present(self.imagePickerController, animated: true, completion: nil)
            }
            
        }
    }
}

extension ImageUpload: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        let image = info[.originalImage] as! UIImage
        self.block!(image)
    }
}


